<?php
namespace App\Services\Payment;

use App\Jobs\OrderCallbackJob;
use App\Models\ConstCode;
use App\Models\ConstCodeArray;
use App\Models\MysqlDb\CompanyModel;
use App\Models\MysqlDb\PaymentAlipayModel;
use App\Models\MysqlDb\PaymentOrderModel;
use App\Models\MysqlDb\PaymentWechatModel;
use App\Models\StatusCode;
use App\Services\CommonReturn;
use App\Services\CommonServices;
use App\Services\Payment\Order\PayServices;
use Yansongda\Pay\Pay;

/**
 * Class PayService
 * @package app\common\service
 * @Author: TinyMeng <666@majiameng.com>
 * @Created: 2020/8/14
 */
class PayNotifyService extends PayServices {

    /**
     * @return void
     */
    public function getCompany()
    {
        //获取公司信息
        $this->company = CompanyModel::getByAppid($this->app_id);
    }

    /**
     * @return string
     * @author: tinymeng <666@majiameng.com>
     * @ctime:  2021/6/10 11:52
     */
    public function wechat(){
        if(empty($this->company)){
            return $this->error();
        }
        $this->config = (new ConfigService)->getParamsConfig($this->company,ConstCodeArray::getPayMent(ConstCode::PAYMENT_WECHAT));
        if(empty($this->config)){
            $this->log(__FUNCTION__.' app_id not found');//记录日志
            return $this->error();
        }
        //验证回调参数
        $service = Pay::wechat($this->config);

        try {
            $result = $service->callback()->toArray();
            $this->log(__FUNCTION__.' callback to array',$result);

                /**
                 * 支付成功异步回调
                 */
//                退款成功
//                $result = '{"id":"d841c599-8c03-5112-ad80-5809772e202f","create_time":"2024-08-04T14:17:46+08:00","resource_type":"encrypt-resource","event_type":"REFUND.SUCCESS","summary":"\u9000\u6b3e\u6210\u529f","resource":{"original_type":"refund","algorithm":"AEAD_AES_256_GCM","ciphertext":{"sp_mchid":"1679165617","sub_mchid":"1681351274","out_trade_no":"202408041325262045","transaction_id":"4200002416202408047005961144","out_refund_no":"T2024080414174362670","refund_id":"50303700182024080473204229972","refund_status":"SUCCESS","success_time":"2024-08-04T14:17:46+08:00","amount":{"total":1,"refund":1,"payer_total":1,"payer_refund":1},"user_received_account":"\u652f\u4ed8\u7528\u6237\u96f6\u94b1"},"associated_data":"refund","nonce":"lUUQNrDgKG4Z"}}';
//                支付成功
//                $result = '{"id":"e0bdf026-cb9a-52b2-a2a0-f9c4f0ba752e","create_time":"2024-08-04T13:25:33+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"\u652f\u4ed8\u6210\u529f","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":{"sp_mchid":"1679165617","sub_mchid":"1681351274","sp_appid":"wx50bb73bbccb39f48","out_trade_no":"202408041325262045","transaction_id":"4200002416202408047005961144","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"\u652f\u4ed8\u6210\u529f","bank_type":"OTHERS","attach":"","success_time":"2024-08-04T13:25:33+08:00","payer":{"sp_openid":"ofOsS5xLJ-qyWPltkFqdwVNgeIy4","sub_openid":""},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}},"associated_data":"transaction","nonce":"iH6q9Lrj5FVK"}}';
//                $result = json_decode($result,true);
            $data = $result['resource']['ciphertext'];
            $out_trade_no = $data['out_trade_no'];
            if($result['event_type'] == 'TRANSACTION.SUCCESS' && $data['trade_state'] == 'SUCCESS'){
                //记录微信支付信息
                PaymentWechatModel::add($result,$this->company['id']);

                $success_time = CommonServices::dateTimeSetZone($data['success_time'])->getTimestamp();
                //修改支付状态
                $total_fee = bcdiv($data['amount']['total'], 100,2);
                $pay = $this->isPay($this->app_id,$data['out_trade_no'],$total_fee,$success_time,$data['transaction_id']);
                if($pay == false){
                    $this->log(__FUNCTION__.' 订单:'.$out_trade_no.'订单不存在');//记录日志
                }else{
                    //回调订单状态
                    OrderCallbackJob::dispatch($pay);
                    $this->log(__FUNCTION__.' 订单:'.$out_trade_no.'状态支付成功');//记录日志
                }
            }elseif($result['event_type'] == 'REFUND.SUCCESS'){
                $this->log(__FUNCTION__.' 订单:'.$out_trade_no.' 退款成功');//记录日志
            }else{
                $this->log(__FUNCTION__.' 订单:'.$out_trade_no.'状态支付失败');//记录日志
            }
            //回调成功
            return $this->success();
        }catch (\Exception $exception){
            $this->log(__FUNCTION__.' error:',$exception);//记录日志
            return $this->error();
        }
    }


    /**
     * @Author: TinyMeng <666@majiameng.com>
     * @return mixed
     */
    public function aliPay(){

        $this->config = (new ConfigService)->getParamsConfig($this->company,ConstCodeArray::getPayMent(ConstCode::PAYMENT_ALIPAY));
        if(empty($this->config)){
            $this->log(__FUNCTION__.' app_id not found');//记录日志
            CommonReturn::fail(StatusCode::COMMON_NO_DATA_EXIST,'app_id not found');
        }

        $service = Pay::alipay($this->config);
        /**
         * 即时到帐接口——交易状态列表

        交易状态操作：支付宝有交易记录，没付款
        交易状态（trade_status）：WAIT_BUYER_PAY
        备注：通知不会返回，不能申请修改。

        交易状态操作：交易完成
        交易状态（trade_status）：TRADE_FINISHED
        备注：普通即时到帐状态下

        交易状态操作：交易完成
        交易状态（trade_status）：TRADE_SUCCESS
        备注：高级即时到帐状态下

        交易状态操作：交易关闭
        交易状态（trade_status）：TRADE_CLOSED
        备注：默认通知不返回，可申请修改（条件需开通高级即时到帐功能，且非常需要退款的同步）。出现该情况在开通高级即时到帐时的人工操作退款时、买家没付款系统自动或卖家手动关闭了该笔交易
         */
        try{
            /**
             * 验证签名
             * @var  $data
             * {"gmt_create":"2020-08-14 14:20:49","charset":"utf-8","seller_email":"coolwork2088@gmail.com","subject":"测试订单","sign":"cuij+kEDak/KqqtWZ8IkcNzUM2LTNYtQtk8AO+G3GcAEL/aCP5V/m3VywaaaEpGTgH0KEhKBXdAQpZ52pLnvGlr6X1tc04m2ot/dxB2bkgVBRl/IRpwDdckbMId5+9WmtG5PaPRZGUv1OQb11Gwq23ts3ky0Hbzk2fAQJJIzIjsO35fwJLS2IRO/AD52PQu6n43Ox7IFjjfCHUrqrsgr6TE+S1qFSgefOkTvpuFSW1QVVIsZOoy7VBZPx8oJwR/6YzfDJ4MC+hOk+BPYRl56Mo7OCWajuJWYwucUkoAyVSP3SDsFu6tAjQr9Sjzv4EEeQEBlUVWz/UbEp3nbv5dIrQ==","buyer_id":"2088612452391258","invoice_amount":"0.01","notify_id":"2020081400222142057091251409308034","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","app_id":"2019092667810895","buyer_pay_amount":"0.01","sign_type":"RSA2","seller_id":"2088531035267725","gmt_payment":"2020-08-14 14:20:57","notify_time":"2020-08-14 14:20:58","version":"1.0","out_trade_no":"11345678974166665","total_amount":"0.01","trade_no":"2020081422001491251422421541","auth_app_id":"2019092667810895","buyer_logon_id":"879***@qq.com","point_amount":"0.00"}
             */
            $data = $service->callback()->toArray();
            $this->log(__FUNCTION__.' callback to array',$data);
//            $data = '{"gmt_create":"2024-06-07 22:25:13","charset":"utf-8","seller_email":"ali@majiameng.com","subject":"\u966a\u62a4\u8ba2\u5355-2024060712224167601-\u626b\u4e8c\u7ef4\u7801","sign":"WF8MbbmamZ1XjPpebFiSP7hK50cMgmjs1xuekGzCORG8Euf2PTXau3NkiwBadwbm6rgMPtEI2cmtan1LqNImJC560OZM\/Vmmahg4a\/8jSOWwZOH1zfTlMXs399DTixAwxVs39n8eLBq+fOHLm6nX4NDwzte7CHjxiRbwmbAG5pKmyaAwjPAl2z+BBc8FKRyUgkBgujvtVYmJoekLUx9zv5oK4Nm2Jdr0Ts\/j0DNrAuAbrjSSSwgoNpNQKop6ZbHehwyqXh6Ez469wvC9ui7zEf3hdI\/I03HxnNv+Pv4BrBlurzOjeDovxJKy1ZVBKnICn7mWzMJ9CqUXi2LBo025ow==","buyer_id":"2088612452391258","invoice_amount":"0.01","notify_id":"2024060701222222513091251423918430","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","buyer_pay_amount":"0.01","app_id":"2021003164645255","sign_type":"RSA2","seller_id":"2088441180666420","gmt_payment":"2024-06-07 22:25:13","notify_time":"2024-06-07 22:25:13","version":"1.0","out_trade_no":"202406072225055730","total_amount":"0.01","trade_no":"2024060722001491251453411788","auth_app_id":"2021003164645255","buyer_logon_id":"879***@qq.com","point_amount":"0.00"}';
//            $data = json_decode($data,true);
            $out_trade_no = $data['out_trade_no'];
            if($data['trade_status'] == 'TRADE_CLOSED' || !empty($data['refund_fee'])){
                //退款成功
                $this->log(__FUNCTION__.' 订单:'.$out_trade_no.' 退款成功');//记录日志
            }elseif($data['trade_status'] == 'TRADE_SUCCESS'){
                //记录微信支付信息
                PayMentAlipayModel::add($data,$this->company['id']);
                $success_time = strtotime($data['gmt_payment']);

                //修改支付状态
                $total_fee = $data['total_amount'];
                $pay = $this->isPay($this->app_id,$data['out_trade_no'],$total_fee,$success_time,$data['trade_no']);
                if($pay == false){
                    $this->log(__FUNCTION__.' 订单:'.$out_trade_no.'订单不存在');//记录日志
                }else{
                    //回调订单状态
                    OrderCallbackJob::dispatch($pay);
                    $this->log(__FUNCTION__.' 订单:'.$out_trade_no.'状态支付成功');//记录日志
                }
            }else{
                $this->log(__FUNCTION__.' 订单:'.$out_trade_no.'状态支付失败');//记录日志
            }

            /** 支付宝回调成功 */
            return $this->success();
        }catch (\Exception $exception){
            $this->log(__FUNCTION__.' error:',$exception);//记录日志
            return $this->error();
        }
    }

    /**
     * @return void
     */
    public function alipayReturn(){
        $this->config = (new ConfigService)->getParamsConfig($this->company,ConstCodeArray::getPayMent(ConstCode::PAYMENT_ALIPAY));
        if(empty($this->config)){
            $this->log(__FUNCTION__.' app_id not found');//记录日志
            CommonReturn::fail(StatusCode::COMMON_NO_DATA_EXIST,'app_id not found');
        }

        try{
            // sign验证
            $service = Pay::alipay($this->config);
            $data = $service->callback()->toArray();
    //        $data = '{"charset":"utf-8","out_trade_no":"202406072225055730","method":"alipay.trade.wap.pay.return","total_amount":"0.01","sign":"aim6w2Dsfe25VvA2uF5EwDmAqtmrHth5nvKo6H0c8unXlDw08qA67COioq2CDNzZUK1NccB1xhMuTs1IVzHmFhpkJpqVw9bQF83CU6CHrRVytrDN6rszEAVF95wOsrv1ONEn0yKK1V+N5cH0JXx+I7QtUHehaapfTJFK46MvIUVd0qnGiFAjX0qioWuc\/DAjlcf9iBHutQNXcggah54H3xg8mHkNlEk5rJBKm0Co46xjCsA8P9C\/nikv2dIagS+cZ\/Q0oNH2Yh\/mFiff+JwP0E4MIq3FbKQYjZjBApnmxtkWofdFNP3bbCK5\/ZkQjCFQXcq6toRsZn98rabxOXpNfw==","trade_no":"2024060722001491251453411788","auth_app_id":"2021003164645255","version":"1.0","app_id":"2021003164645255","sign_type":"RSA2","seller_id":"2088441180666420","timestamp":"2024-06-07 22:25:13"}';
    //        $data = json_decode($data,true);

            //第三方支付信息
            $order = PaymentOrderModel::getOrderByOutTradeNo($this->app_id,$data['out_trade_no']);
            if(empty($order)){
                CommonReturn::fail(StatusCode::COMMON_NO_DATA_EXIST);
            }
            $params = [
                'out_trade_no'=>$order['out_trade_no'],
                'transaction_id'=>$order['transaction_id'],
                'pay_time'=>empty($order['pay_time']) ? strtotime($data['timestamp']) : $order['pay_time'],
                'amount'=>empty($order['amount']) ? $data['total_amount'] : $order['amount'],
            ];
            if(empty($order['return_url'])){
                echo '支付成功';exit();
            }else{
                $return_url = $order['return_url'];
            }

            $payment_url = $return_url.'?'.http_build_query($params);
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: ".$payment_url);
            exit();
        }catch (\Exception $exception){
            $this->log(__FUNCTION__.' error:',$exception);//记录日志
            return $this->error();
        }
    }

}
